package com.neo.dao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hankcs.hanlp.seg.common.Term;
import com.alibaba.fastjson.JSON;
import static org.neo4j.driver.v1.Values.parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.neo4j.driver.v1.AuthTokens;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.TransactionWork;

import static org.neo4j.driver.v1.Values.parameters;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Configuration
@Component
public class NeoConnect {
    private Driver driver;

    @Value("${neo4j.host}")
    private  String HOST;

    @Value("${neo4j.port}")
    private  String PORT;

    @Value("${neo4j.username}")
    private  String USERNAME;

    @Value("${neo4j.password}")
    private  String PASSWORD;

    public void GraphDataBaseConnection() {
        String uri = "bolt://".concat(HOST).concat(":").concat(PORT);
        driver = GraphDatabase.driver(uri, AuthTokens.basic(USERNAME, PASSWORD));
    }

    public void close() {
        driver.close();
    }


    public  List<JSONObject> execCypher(String cypher) {
        if(driver==null){
          GraphDataBaseConnection();
        }

        List<JSONObject> results = new ArrayList<>();

        try (Session session = driver.session()) {
            StatementResult result = session.run(cypher);
            // Each Cypher execution returns a stream of records.
            while (result.hasNext()) {
                Record record = result.next();
                Map<String, Object> date = record.asMap();
                JSONObject jsonObj=new JSONObject(date);
                System.err.println(jsonObj.toJSONString());
                // Values can be extracted from a record by index or name.
                //results.add(date);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return results;
    }
}
